﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI;
using YArchitech.Controls;

namespace YArchitech.Revit
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class UpdateLinkedDocument : HYNoTranExternalCommand
	{
		public override Result HYExecute()
		{
			try
			{
				string empty = string.Empty;
				OpenFileDialog openFileDialog = new OpenFileDialog();
				openFileDialog.Filter = "数据更新文件|*.xml";
				openFileDialog.RestoreDirectory = true;
				openFileDialog.FilterIndex = 1;
				if (openFileDialog.ShowDialog() != DialogResult.OK)
				{
					return Autodesk.Revit.UI.Result.Cancelled;
				}
				string fileName = openFileDialog.FileName;
				string text = base.Doc.Title;
				if (text.LastIndexOf(".rvt") > 0)
				{
					text = text.Substring(0, text.LastIndexOf(".rvt"));
				}
				MajorSystemType type = MajorSystemType.UndefinedSystem;
				List<HYUpdateElementInfo> nodes = HYUpdateLinkedDocXML.LoadXMLToElementList(fileName, text, ref type);
				ElementsUpdater elementsUpdater = this.CreateUpdater(type, nodes);
				if (elementsUpdater.UpdateElementInfo())
				{
					YJKMessageBox.Information("更新数据成功！");
				}
				else
				{
					YJKMessageBox.Error(string.Format("更新数据失败: {0}！", elementsUpdater.FailedString));
				}
			}
			catch (Exception ex)
			{
				YJKMessageBox.Show(ex.Message);
				return Autodesk.Revit.UI.Result.Failed;
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		public override void FilterProcess()
		{
            base.FilterViewType.Add((Autodesk.Revit.DB.ViewType)1);
            base.FilterViewType.Add((Autodesk.Revit.DB.ViewType)2);
            base.FilterViewType.Add((Autodesk.Revit.DB.ViewType)4);
			base.FilterProcess();
		}

		protected ElementsUpdater CreateUpdater(MajorSystemType type, List<HYUpdateElementInfo> nodes)
		{
			ElementsUpdater result;
			switch (type)
			{
			case MajorSystemType.PlumbingSystem:
				result = new PlumbingSystemUpdater(base.Doc, nodes);
				break;
			case MajorSystemType.DuctOfHVACSystem:
				result = new HVACDuctUpdater(base.Doc, nodes);
				break;
			case MajorSystemType.PipeOfHVACSystem:
				result = new HVACPipeUpdater(base.Doc, nodes);
				break;
			default:
				result = new ElementsUpdater(base.Doc, nodes);
				break;
			}
			return result;
		}
	}
}
